<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px" class="queryForms">
			<el-form-item label="返修任务单" prop="recordNumber">
				<el-input v-model="queryParams.recordNumber" placeholder="请输入返修任务单" clearable @keyup.enter.native="handleQuery" maxlength="20" show-word-limit  />
			</el-form-item>
			<el-form-item label="产品型号" prop="recordNumber">
				<el-input v-model="queryParams.recordNumber" placeholder="请输入产品型号" clearable @keyup.enter.native="handleQuery" maxlength="20" show-word-limit  />
			</el-form-item>
			<el-form-item label="零组件名称" prop="recordNumber">
				<el-input v-model="queryParams.recordNumber" placeholder="请输入零组件名称" clearable @keyup.enter.native="handleQuery" maxlength="20" show-word-limit  />
			</el-form-item>
			<el-form-item label="状态" prop="inspectStatus">
				<el-select v-model="queryParams.inspectStatus" placeholder="请选择">
					<el-option v-for="dict in dict.type.inspect_status" :key="dict.value" :label="dict.label" :value="dict.value"> </el-option>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" icon="el-icon-plus" size="mini" @click="handleOutsource" v-hasPermi="['synthesize:outsource:oentrancelist:out']">外委</el-button>
			</el-col>
			生成表单
			<right-toolbar @changeTableData="changeTableData" menuNames="oentrancelist55" :showSearch.sync="showSearch" @queryTable="handleQuery" :columns.sync="columns" perm="synthesize:outsource:oentrancelist:index"></right-toolbar>
		</el-row>

		<div :class="sidebar.opened && eleTabTop <= 85 ? 'eleTab' : !sidebar.opened && eleTabTop <= 85 ? 'eleTabs' : ''" class="informationTab" ref="eleTab">
			<el-table ref="table" @row-click="row_click" v-loading="loading" :data="EntrancelistList" @selection-change="handleSelectionChange" row-key="id" lazy :load="loadListDes" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"  border height="100%">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column label="序号" align="center" type="index" width="55" >
           <template slot-scope="scope">
               <div>{{scope.row.sort}}</div>
           </template>
        </el-table-column>

				<el-table-column label="编号" prop="recordNumber" min-width="150" :show-overflow-tooltip="true" v-if="columns[0].visible" />
				<el-table-column label="外委日期" prop="outsourcingDate" min-width="150" :show-overflow-tooltip="true" v-if="columns[1].visible" />
				<el-table-column label="返修任务单" prop="repairNumber" min-width="150" :show-overflow-tooltip="true" v-if="columns[2].visible" />
				<el-table-column label="生产批次" prop="productionBatch" min-width="150" :show-overflow-tooltip="true" v-if="columns[3].visible" />
				<el-table-column label="产品名称" prop="productName" min-width="150" :show-overflow-tooltip="true" v-if="columns[4].visible" />
				<el-table-column label="产品型号" prop="productModel" min-width="150" :show-overflow-tooltip="true" v-if="columns[5].visible" />
				<el-table-column label="产品编号" prop="productNumber" min-width="150" :show-overflow-tooltip="true" v-if="columns[6].visible" />
				<el-table-column label="零件组名称" prop="partName" min-width="150" :show-overflow-tooltip="true" v-if="columns[7].visible" />
				<el-table-column label="零件组编码" prop="partFigure" min-width="150" :show-overflow-tooltip="true" v-if="columns[8].visible" />
				<el-table-column label="数量" prop="quantityquantity" min-width="150" :show-overflow-tooltip="true" v-if="columns[9].visible" />
				<el-table-column label="状态" prop="registrationStatus" min-width="150" :show-overflow-tooltip="true" v-if="columns[10].visible">
					<template slot-scope="scope">
						<dict-tag :options="dict.type.inspect_status" :value="scope.row.registrationStatus" />
					</template>
				</el-table-column>
				<el-table-column label="操作" class-name="small-padding fixed-width" width="122px" fixed="right">
					<template slot-scope="scope">
						<section v-if="scope.row.hasChildren">
							<el-button size="mini" type="text" icon="el-icon-wallet" @click="handleAnnex(scope.row)" v-hasPermi="['synthesize:outsource:oentrancelist:annex']">附件</el-button>
						</section>
						<section v-else>
							<el-button size="mini" type="text" icon="el-icon-wallet" @click="handleAnnex2(scope.row)" v-hasPermi="['synthesize:outsource:oentrancelist:annex2']">附件</el-button>
						</section>
					</template>
				</el-table-column>
			</el-table>
		</div>

		<pagination menuNames="Pagination60" v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

		<!-- 添加或修改发票对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="900px" append-to-body v-dialogDrag>
			<el-form ref="form" class="add-form1" :model="form" :rules="rules" label-width="100px">
				<el-form-item label="记录编号" prop="recordNumber">
					<el-input v-model="form.recordNumber" placeholder="请输入记录编号" maxlength="20" show-word-limit  />
				</el-form-item>
				<el-form-item label="编号" prop="serialNumber">
					<el-input v-model="form.serialNumber" placeholder="请输入编号" maxlength="20" show-word-limit  />
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import { listEntrancelist, listEntrancelistChild, delEntrancelist, submitOutsource } from "@/api/synthesize/outsource/oentrancelist"
import { mapGetters } from "vuex"
import { getUserList,getcolumn } from "@/api/selectList"
export default {
	name: "maintain",
	dicts: ["default_approve", "product_intact_state", "inspect_status"],
	computed: {
		...mapGetters(["sidebar"])
	},
	data() {
		return {
			eleTabTop: 0, //表格容器距浏览器顶部距离
			testval: undefined,
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			rows: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 设备保养计划表格数据
			EntrancelistList: [],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				deviceName: undefined,
				inspectStatus: undefined,
				applyTime: undefined
			},
			// 表单参数
			form: {},
			// 表单校验
			rules: {
				recordNumber: [{ required: true, message: "请输入记录编号", trigger: "blur" }],
				serialNumber: [{ required: true, message: "请输入编号", trigger: "blur" }]
			},
			deviceList: [],
			// 更新树刷新
			treeMap: new Map(),
			// 审批数据
			openApprove: false,
			approveRow: undefined,
			// 生产计划
			isOne: false,
			disabled: false,
			// 审批流程
			// openRecords: false,
			approveRecord: [],
			treetablekey: Math.random(),
			// 用户列表
			userList: [],
			// 列信息
			columns: [
				{ key: 0, label: `编号`, visible: true },
				{ key: 1, label: `外委日期`, visible: true },
				{ key: 2, label: `返修任务单`, visible: true },
				{ key: 3, label: `生产批次`, visible: true },
				{ key: 4, label: `产品名称`, visible: true },
				{ key: 5, label: `产品型号`, visible: true },
				{ key: 6, label: `产品编号`, visible: true },
				{ key: 7, label: `零件组名称`, visible: true },
				{ key: 8, label: `零件组编码`, visible: true },
				{ key: 9, label: `数量`, visible: true },
				{ key: 10, label: `状态`, visible: true }
			]
		}
	},
	created() {
		this.getSize()
		this.getUserList()
	},
	mounted() {
		// 滚动条的获取
		this.handleScrollx()
		window.addEventListener("scroll", this.handleScrollx, true)
	},
	activated() {
		this.getSize()
		//获取表格容器距页面头部的距离
		this.handleScrollx()
	},
	destroyed() {
		window.removeEventListener("scroll", this.handleScrollx, true)
	},
	methods: {
    getSize() {
			getcolumn({ pageName: "Pagination60" }).then(response => {
				this.queryParams.pageSize = response.data.length ? (response.data[0].limit ? response.data[0].limit : 10) : 10
				this.getList()
			})
		},
		// 单击表格行
		row_click(row, column, event) {
			if (column && column.label == "操作") {
				return
			} else {
				this.$refs.table.toggleRowSelection(row)
			}
		},
		changeTableData() {
			this.$nextTick(() => {
				this.$refs.table.doLayout()
			})
		},

		//获取表格容器距页面头部的距离
		handleScrollx() {
			this.eleTabTop = this.$refs.eleTab.getBoundingClientRect().top
		},
		// 获取用户下拉选
		getUserList() {
			getUserList().then(res => {
				this.userList = res.rows
			})
		},
		//
		changeUser() {
			let cur = this.userList.find(item => {
				return item.userId == this.form.recipientId
			})
			this.form.recipientName = cur.nickName
		},
		/** 查询设备保养计划列表 */
		getList() {
			this.loading = true
			listEntrancelist(this.queryParams).then(response => {
				this.EntrancelistList = response.rows
				this.EntrancelistList.forEach((item,index) => {
					item.hasChildren = true
           item.sort = index+1
          this.$refs.table.toggleRowExpansion(item, false);
				})
				this.total = response.total
				this.loading = false
			})
		},
		// 获取列表详情
		async loadListDes(tree, treeNode, resolve) {
			if (!this.treeMap.has(tree.id)) {
				this.treeMap.set(tree.id, {
					treeNode,
					resolve
				})
			}
			let data = {
				id: tree.id,
				deviceName: this.queryParams.deviceName,
				inspectStatus: this.queryParams.inspectStatus,
				applyTime: this.queryParams.applyTime
			}
			let ret = await listEntrancelistChild(data)
			ret.rows.forEach((item,index) => {
				// 父子id会冲突
				item.id = "c" + item.id
         item.sort = index+1
			})
			resolve(ret.rows)
		},
		// 取消按钮
		cancel() {
			this.$refs.table.clearSelection()
			this.open = false
			this.reset()
		},
		// 表单重置
		reset() {
			this.form = {
				idList: undefined,
				recordNumber: undefined,
				serialNumber: undefined
			}
			this.resetForm("form")
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1
			this.getList()
			this.treetablekey = Math.random()
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm("queryForm")
			this.handleQuery()
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.id)
			this.rows = selection
			this.single = selection.length !== 1
			this.multiple = !selection.length
		},
		/** 提交外委 */
		submitForm() {
			this.$refs["form"].validate(valid => {
				if (valid) {
					submitOutsource(this.form).then(response => {
						this.$modal.msgSuccess("操作成功")
						this.open = false
						this.$refs.table.clearSelection()
						this.refreshTree()
					})
				}
			})
		},
		// 附件
		handleAnnex(row) {
			this.$router.push({
				path: "/attachment/attachmentUpload",
				query: {
					TableId: row.id,
					typeId: 35,
					perm: "synthesize:outsource:oentrancelist:annex"
				}
			})
		},
		handleAnnex2(row) {
			let id = row.id.replace("c", "")
			this.$router.push({
				path: "/attachment/attachmentUpload",
				query: {
					TableId: id,
					typeId: 36,
					perm: "synthesize:outsource:oentrancelist:annex2"
				}
			})
		},

		checkIds() {
			// 判断ids
			if (this.ids.length == 0) {
				this.$modal.msg("请选择产品")
				return false
			} else {
				// 判断是否选中了父级返修任务
				let checkp = this.rows.find(item => {
					return Number(item.id) > 0
				})
				if (checkp) {
					this.$modal.msg("只能选择子类产品")
					return false
				}
			}
			let ids = this.ids.map(item => {
				return item.replace("c", "")
			})
			return ids
		},
		// 更新树
		refreshTree() {
			this.rows = []
			this.ids = []
			// 这个刷新checkbox有问题
			// this.treeMap.forEach((item, idx) => {
			//   this.loadListDes({ id: idx }, item.treeNode, item.resolve);
			// });
			this.treetablekey = Math.random()
		},
		// 下发
		handleOutsource(row) {
			let ids = this.checkIds()
			if (!ids) {
				return false
			}
			this.reset()
			this.form.idList = ids
			this.open = true
			this.title = "外委"
		}
	}
}
</script>

<style lang="scss" scoped>
::v-deep .el-table__fixed-header-wrapper .fixed-width {
	width: 122px !important;
}
</style>
